﻿#include "BaseTask.h"
#include "TaskThread.h"
#include <random>
BaseTask::BaseTask()
{
}

BaseTask::~BaseTask()
{
}

void BaseTask::initialize(TaskThread *taskThread)
{
    m_taskThread = taskThread;
}

WuDong &BaseTask::wd()
{
    return m_taskThread->m_wudong;
}

bool BaseTask::getRolePos(long &x, long &y)
{
    // 识别坐标
    //  x  785,143,826,169
    //  y  828,147,879,170

    long lRet;
    std::vector<std::wstring> ocr_results;
    std::vector<cv::Rect> rects;

    wd().UseDict(L"坐标", &lRet);
    wd().Ocr(785, 143, 826, 169, 0.95, ocr_results, rects);
    std::wstring ret_str = wd().JointResult(ocr_results);
    ocr_results.clear();
    rects.clear();
    wd().Ocr(828, 147, 879, 170, 0.95, ocr_results, rects);
    std::wstring ret_str1 = wd().JointResult(ocr_results);

    if (!ret_str.empty() && !ret_str1.empty())
    {
        x = _wtoi(ret_str.c_str());
        y = _wtoi(ret_str1.c_str());
        role_x_ = x;
        role_y_ = y;

        return true;
    }

    return false;
}

bool BaseTask::isRoleMoving()
{
    static long last_x = 0;
    static long last_y = 0;
    static long last_update_time = 0;
    static bool is_moving = false;
    long x, y;
    long current_time = GetTickCount();
    if (current_time - last_update_time > 1000)
    {
        if (!getRolePos(x, y))
        {
            last_x = 0;
            last_y = 0;
            last_update_time = 0;
            return false;
        }
        if (x != last_x || y != last_y)
        {
            last_x = x;
            last_y = y;
            is_moving = true;
        }
        else
        {
            is_moving = false;
        }
        last_update_time = current_time;
    }
    return is_moving;
}

bool BaseTask::attackMonster()
{
    static bool is_first_attack = true;
    long lRet, retx1, rety1, retx2, rety2;
    wd().FindPic(297, 52, 314, 76, L"血量标志.png", 0.98, &retx1, &rety1, &retx2, &rety2, &lRet);
    if (lRet != 0)
    {

        std::wstring index_str;
        if (is_first_attack)
        {
            index_str = std::to_wstring(1);
            is_first_attack = false;
        }
        else
        {
            std::random_device rd;
            std::mt19937 gen(rd());
            std::uniform_int_distribution<> dis(1, 6);
            int index = dis(gen);
            index_str = std::to_wstring(index);
        }
        wd().KeyPressChar(index_str.c_str(), &lRet);
        return true;
    }
    wd().KeyPress(VK_OEM_3, &lRet);
    wd().Delay(200);
    // 选怪
    wd().KeyPress(VK_TAB, &lRet);
    wd().Delay(200);
    is_first_attack = true;
    return false;
}
